/*
 * Tribunal de Justiça do Paraná
 * Date: 10/11/2006
 */
package info.demo.filter.tag;

import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.JspTagException;
import javax.servlet.http.HttpServletRequest;

public class TagUtils {

    private static final String REQUEST = "request";
    private static final String SESSION = "session";
    private static final String APPLICATION = "application";

    public static int getScope(String scope) {
        int ret = PageContext.PAGE_SCOPE;
        if (REQUEST.equalsIgnoreCase(scope))
            ret = PageContext.REQUEST_SCOPE;
        else if (SESSION.equalsIgnoreCase(scope))
            ret = PageContext.SESSION_SCOPE;
        else if (APPLICATION.equalsIgnoreCase(scope))
            ret = PageContext.APPLICATION_SCOPE;
        return ret;
    }

    public static boolean isAbsoluteUrl(String url) {
        if (url == null)
            return false;

        // Rápida checagem
        int colonPos;
        if ((colonPos = url.indexOf(":")) == -1)
            return false;

        // Se há os dois pontos, verificar se há um URL SCHEME válido
        String scheme = url.substring(0, colonPos);
        return scheme.matches("[a-zA-Z+.-]*");
    }


    public static String resolveUrl(String url, String context, PageContext pageContext) throws JspTagException {
        if (TagUtils.isAbsoluteUrl(url))
            return url;

        // Normaliza a URL relativa junto com o contexto
        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
        if (context == null) {
            if (url.startsWith("/"))
                return (request.getContextPath() + url);
            else
                return url;
        } else {
            if (!context.startsWith("/") || !url.startsWith("/")) {
                throw new JspTagException("In URL tags, when the \"context\" attribute is specified, values of both" +
                        " \"context\" and \"url\" must start with \"/\".");
            }
            if (context.equals("/")) {
                // Não produz string iniciando com "//"
                return url;
            } else {
                return context + url;
            }
        }
        
    }

}
